import requests
from datetime import datetime
from typing import List, Dict, Union
from django.conf import settings

class NotificationService:
    def __init__(self):
        self.wechat_token = settings.PUSHPLUS_TOKEN  # 从settings中读取
        self.pushplus_url = "https://www.pushplus.plus/send"

    def format_trading_suggestions(self, suggestions: List[Dict]) -> str:
        """将交易建议格式化为Markdown消息"""
        if not suggestions:
            return "暂无交易建议"

        msg = "# 今日股票交易建议\n\n"
        msg += f"生成时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"

        for suggestion in suggestions:
            msg += f"## {suggestion['name']}（{suggestion['code']}）\n\n"
            msg += f"- 建议：**{suggestion['suggestion']}**\n"
            msg += f"- 原因：{suggestion['reason']}\n"
            
            if suggestion['suggestion'] == '买入':
                msg += f"- 当前价格：¥{suggestion['current_price']}\n"
                msg += f"- 止盈价格：¥{suggestion['profit_target']:.2f}\n"
                msg += f"- 止损价格：¥{suggestion['stop_loss']:.2f}\n"
            
            msg += "\n---\n\n"

        return msg

    def send_wechat(self, content: Union[str, List[Dict]], title: str = None) -> bool:
        """
        发送消息到微信
        :param content: 可以是格式化好的字符串或交易建议列表
        :param title: 消息标题，如果为None则使用默认格式
        :return: 是否发送成功
        """
        try:
            # 如果传入的是交易建议列表，先格式化
            if isinstance(content, list):
                content = self.format_trading_suggestions(content)

            # 生成标题
            if title is None:
                title = f"{datetime.now().strftime('%Y%m%d')}股票量化分析"

            # 准备请求数据
            data = {
                'token': self.wechat_token,
                'content': content,
                'title': title,
                'template': 'markdown'
            }

            # 发送请求
            response = requests.post(url=self.pushplus_url, data=data)
            result = response.json()

            # 检查响应
            if response.status_code == 200 and result.get('code') == 200:
                print(f"消息发送成功: {title}")
                return True
            else:
                print(f"消息发送失败: {result.get('msg', '未知错误')}")
                return False

        except Exception as e:
            print(f"发送消息时发生错误: {str(e)}")
            return False

    def send_miniprogram(self, content):
        """
        发送消息到小程序（示例方法，需要根据实际小程序API实现）
        """
        # TODO: 实现小程序消息推送
        pass 